<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb5">
      <el-col :span="1.5">
        <!-- <el-button plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['system:recovery:export']">导出</el-button> -->

          <el-button
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:conn:remove']"
          >删除</el-button>

      </el-col>
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px"
        class="el-form-search">
        <el-form-item label="连接名称" prop="connName" class="el-form-search-item">
          <el-input v-model="queryParams.connName" placeholder="请输入连接名称" clearable size="mini"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="数据库名称" prop="dbName" class="el-form-search-item">
          <el-input v-model="queryParams.dbName" placeholder="请输入数据库名称" clearable size="mini"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item class="el-form-search-item">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-row>

    <el-table :height="tableHeight" v-loading="loading" :data="recoveryList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" />
      <el-table-column label="连接名称" align="center" prop="connName" />
      <el-table-column label="数据库名称" align="center" prop="dbName" />
      <el-table-column label="开始时间" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime) }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="恢复的表清单" align="center" prop="tables">
        <template slot-scope="scope">
          <span>{{ scope.row.tables }}</span>
        </template>
      </el-table-column> -->
      <!--scope.row.endTime ==null 别分未结束  -->
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.endTime == null" type="danger">未结束</el-tag>
          <el-tag v-else type="success">已结束</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:recovery:edit']">详情</el-button>
          <el-button 
            v-if="scope.row.endTime != null"
          size="mini" type="text" icon="el-icon-download" @click="handleDownload(scope.row)"
            v-hasPermi="['system:recovery:edit']">下载日志</el-button>



        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改数据库恢复记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body :close-on-click-modal="false"
      v-dialogDrag>

      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="表清单" prop="tables">
          <div style="height:150px;overflow-y: auto;">
            <el-tag type="success" v-for="table in form.tableList" style="margin-right: 10px">
            {{ table }}
          </el-tag>
          </div>
        </el-form-item>

        <el-form-item label="错误日志" prop="errLogs" v-if="form.endTime!=null">
          <el-input  type="textarea" v-model="form.errLogs" :auto-rows="true" readonly
            :rows="5"></el-input>
        </el-form-item>

 
        <el-form-item label="恢复日志" prop="logs">
          <el-input ref="recoveryMsgTextarea" type="textarea" v-model="form.logs" :auto-rows="true" readonly
            :rows="10"></el-input>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
  
<script>
import { listRecovery, getRecovery, delRecovery, addRecovery, updateRecovery, downloadLog } from "@/api/db/recovery";
import { recoveryLastRowLog } from "@/api/db/conn";

export default {
  name: "Recovery",
  data() {
    return {
      // 表格高度
      tableHeight: document.documentElement.clientHeight - 180,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 数据库恢复记录表格数据
      recoveryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        orderByColumn: "id",
        isAsc: "desc",
        connName: null,
        dbName: null,
        startTime: null,
        endTime: null,
        tables: null,
        logs: null
      },
      // 表单参数
      form: {
        logs:'',
        errLogs:''
      },
      // 表单校验
      rules: {
      },
    };
  },

  watch: {
    'form.logs': {
      handler(newValue) {
        this.$nextTick(() => {
          const textarea = this.$refs.recoveryMsgTextarea.$el.firstChild;
          if (textarea) {
            textarea.scrollTop = textarea.scrollHeight;
          }
        });
      },
      deep: true
    },
    'open': {
      handler(newValue) {
        if (newValue == false) {
          clearTimeout(this.time1)
        }
      }
    }
  },

  created() {
    this.getList();
  },
  methods: {
    /** 查询数据库恢复记录列表 */
    getList() {
      this.loading = true;
      listRecovery(this.queryParams).then(response => {
        this.recoveryList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        connName: null,
        dbName: null,
        startTime: null,
        endTime: null,
        tables: null,
        logs: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleDownload(row) {
      let url ="/db/recovery/downloadLog";
      this.download(url,{recoveryId:row.id},row.connName + '_' + row.dbName + '.log');
    },
    /** 修改按钮操作 */
    handleUpdate(row) {


      const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
     

      //判断是否已经结束
      if (row.endTime == null) {
        this.getRealTimeLog(row, 0);
      }
      //拉取数据
      getRecovery(row.id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "查看详情";
        this.form.tableList = this.form.tables.split("#");
        
        loading.close();

      });
    },


    getRealTimeLog(row, cnt) {
      recoveryLastRowLog({
        recoveryId: row.id
      }).then((resp) => {
        let msg = resp.msg;
        //添加日志
        if (msg.length > 0) {
          msg += '\n';
        }
        this.form.logs += msg;
        if (msg.indexOf('导入成功') !== -1) {
          clearTimeout(this.time1);
          this.$message.success('恢复完成')
        }
        this.time1 = setTimeout(() => {
          cnt++;
          if (cnt % 10 == 0) {
            //判断是否结束
            getRecovery(row.id).then(response => {
              if (response.data.endTime != null) {
                clearTimeout(this.time1);
                this.$message.success('恢复已结束')
                this.form.logs= response.data.logs;
                this.form.errLogs= response.data.errLogs;
              }else{
                this.getRealTimeLog(row, cnt);
              }
            });
          }else{
            this.getRealTimeLog(row, cnt);
          }
        }, 50);
      });
    },





    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateRecovery(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRecovery(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除记录？').then(function () {
        return delRecovery(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/recovery/export', {
        ...this.queryParams
      }, `recovery_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
  